//
//  OrderStaffSelectController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/20.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "OrderStaffSelectController.h"
#import "JFBStaffDS.h"
#import "OrderStaffSelectCell.h"
#import "JFBOrderDS.h"
#import "JFBLoadingAnimation.h"
@interface OrderStaffSelectController ()<UIAlertViewDelegate,UITableViewDataSource, UITableViewDelegate,UIGestureRecognizerDelegate>{
    NSMutableDictionary *_cells;
    NSString *_currentSelectedKey;
    NSUInteger _currentSelectedStaffID;

    BOOL _editStatusEnable;
    NSUInteger _currentStaffID;
    NSUInteger _willDeleteStaffID;
}

- (IBAction)staffEditAction:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) JFBStaffDS *defaultStaffDS;
@property (nonatomic, strong) NSMutableArray *staffs;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *staffTarBarItem;
@end

@implementation OrderStaffSelectController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.staffs = [@[] mutableCopy];
    _cells = [@{} mutableCopy];
    
    _editStatusEnable = false;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y, self.tableView.frame.size.width, self.view.bounds.size.height - 44);
    
    [button setTitle:@"选好了，立即配送" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = ButtonBgColorImportant;
    [self.view addSubview:button];
    button.frame = CGRectMake(0, self.view.bounds.size.height - 44, self.view.bounds.size.width, 44);
    
    [button addTarget:self action:@selector(selectStaffClick:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectStaff:) name:@"selectStaff" object:nil];
    
    [self reload:nil];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if( [segue.identifier isEqualToString:@"editStaffIdentifier"] && _currentStaffID != 0) {
        JFBStaffDS *cds;
        if( self.defaultStaffDS.Id == _currentStaffID ) {
            cds = self.defaultStaffDS;
        } else {
            for(JFBStaffDS *ds in self.staffs) {
                if( ds.Id == _currentStaffID ) {
                    cds = ds;
                    break;
                }
            }
        }
        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
        ctrl.delegate = self;
        ctrl.hidesBottomBarWhenPushed = true;
        ctrl.staff = cds;
    } else {
        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
        ctrl.delegate = self;
        ctrl.hidesBottomBarWhenPushed = true;
        ctrl.staff = nil;
    }
}

-(void)reload{
    [self reload:nil];
}


- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectStaff:(NSNotification *)notification{
    NSUInteger staffID = [[notification.userInfo objectForKey:@"staffID"] intValue];
    _currentSelectedStaffID = staffID;
    
    [_cells enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        OrderStaffSelectCell *cell = (OrderStaffSelectCell*)obj;
        if( cell.staffID != staffID ) {
            [cell.checkBtn setSelected:false];
        } else {
            _currentSelectedKey = key;
        }
    }];
}

-(void)selectStaffClick:(id)sender {
    [JFBOrderDS acceptStaff:^(BOOL isSuccess, JFBOrderDS *order, NSError *error) {
        NSLog(@"分配订单 %lu_%lu", (unsigned long)self.order.ID, (unsigned long)_currentSelectedStaffID);
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"提示"
                              message:isSuccess ? @"操作成功" : @"失败，请稍候重试或致电客服"
                              delegate:self
                              cancelButtonTitle:nil
                              otherButtonTitles:@"确定",nil];
        [alert show];
    } orderID:self.order.ID staffID:_currentSelectedStaffID ];
}


- (void)reload:(__unused id)sender {
    
    [JFBStaffDS loadStaffList:^(NSArray *staffList, NSError *error) {
        NSLog(@"StaffList:%@", staffList);

        self.defaultStaffDS = nil;
        self.staffs = [@[] mutableCopy];
        
        BOOL hasDefault = false;
        for( JFBStaffDS *ds in staffList ) {
            if( ds.isDefault ) {
                hasDefault = true;
                break;
            }
        }
        
        for( JFBStaffDS *ds in staffList ) {
            if( ds.isDefault && self.defaultStaffDS == nil ) {
                self.defaultStaffDS = ds;
            } else {
                [self.staffs addObject:ds];
            }
        }
        [self.tableView reloadData];
    } pager:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 38;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 100, 38)];
    label.text = self.defaultStaffDS && section == 0 ? @"默认配送员" : @"其他配送员";
    label.textColor = [UIColor colorFromHexValue:0x232323];
    label.font = [UIFont fontWithName:nil size:13];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 38)];
    [view addSubview:label];
    return view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.defaultStaffDS ? 2 : 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.defaultStaffDS && section == 0 ? @"默认配送员" : @"其他配送员";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if( self.defaultStaffDS && section == 0 )
        return 1;
    else
        return [self.staffs count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderStaffSelectCell *cell = [[OrderStaffSelectCell alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 38)];
    NSString *key = [NSString stringWithFormat:@"%lu_%lu", (unsigned long)indexPath.section, (unsigned long)indexPath.row];
    [_cells setObject:cell forKey:key];
    
    JFBStaffDS *ds = self.defaultStaffDS && indexPath.section == 0 ? self.defaultStaffDS : self.staffs[indexPath.row];
    
    
    if( ds.isDefault && !_currentSelectedKey ) {
        _currentSelectedKey = [NSString stringWithFormat:@"%lu_%lu", (unsigned long)indexPath.section, (unsigned long)indexPath.row];
    }
    
    cell.staff = ds;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [NSString stringWithFormat:@"%lu_%lu", (unsigned long)indexPath.section, (unsigned long)indexPath.row];
    if( ![key isEqualToString:_currentSelectedKey] ) {
        OrderStaffSelectCell *cell = [_cells objectForKey:key];
        if( cell ) {
            [cell.checkBtn setSelected:true];
            _currentSelectedStaffID = cell.staffID;
            
            OrderStaffSelectCell *otherCell = [_cells objectForKey:_currentSelectedKey];
            [otherCell.checkBtn setSelected:false];
            _currentSelectedKey = key;
        }
    }
}

- (IBAction)staffEditAction:(id)sender {
//    StaffEditController *vc = [[StaffEditController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
    _currentStaffID = 0;
    [self performSegueWithIdentifier:@"editStaffIdentifier" sender:self];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.refreshDelegate reload];
}
-(BOOL)checkPhoneNumberRepeat:(NSString *)phoneString
{
    for(JFBStaffDS *ds in self.staffs) {
        if ([ds.telephone isEqualToString: phoneString]) {
            return NO;
        }
    }
    return YES;
}

@end
